package com.mrkun.vueshop.service;

import com.google.common.collect.Maps;
import com.mrkun.vueshop.DTO.RouterDTO;
import com.mrkun.vueshop.mapper.RouterMapper;
import com.mrkun.vueshop.model.Router;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by yong
 * @date 2020/3/15
 */
@Service
public class RouterService {
    @Autowired
    private RouterMapper routerMapper;

    /**
     * 得到树形菜单列表
     * @return 菜单列表
     */
    public List<RouterDTO> getMenuTreeList() {
        List<Router> routers = routerMapper.getAllRouter(); //查询所有数据
        List<RouterDTO> routerDTOList = new ArrayList<>();
        for (Router router : routers){
            RouterDTO routerDTO = new RouterDTO();
            BeanUtils.copyProperties(router,routerDTO);
            routerDTOList.add(routerDTO);
        }

        List<RouterDTO> rootList = new ArrayList<>(); //根节点对象存放到这里
        List<RouterDTO> bodyList = new ArrayList<>(); //其他节点存放到这里，可以包含根节点
        for (RouterDTO routerDTO: routerDTOList) {
            if(routerDTO != null) {
                if (routerDTO.getRouterParentId()== 0) {
                    rootList.add(routerDTO);//所有父节点数据放进去
                } else {
                    bodyList.add(routerDTO); //其他节点数据也放进去
                }
            }
        }
        List<RouterDTO> stc = getTree(rootList,bodyList);//组装的树返给前端sb
        return stc;
    }


    public List<RouterDTO> getTree(List<RouterDTO> rootList,List<RouterDTO> bodyList){
        if(bodyList != null && !bodyList.isEmpty()){
            //声明一个map，用来过滤已操作过的数据
            Map<Integer,Integer> map1 = new HashMap<>(bodyList.size());
            //Map<Integer,Integer> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree,bodyList,map1));
            return rootList;
        }
        return null;
    }
    private void getChild(RouterDTO parent,List<RouterDTO>bodyList, Map<Integer,Integer> map){
        List<RouterDTO>childList = new ArrayList<>();
        bodyList.stream().filter(c->!map.containsKey(c.getRouterId()))
                .filter(c->c.getRouterParentId().equals(parent.getRouterId()))
                .forEach(c->{
                    map.put(c.getRouterId(),c.getRouterParentId());
                    getChild(c,bodyList,map);
                    childList.add(c);
                });

        parent.setChildren(childList);
    }
}
